//
//  YuanXinKit.m
//  YuanXinKit
//
//  Created by 晏德智 on 16/9/20.
//  Copyright © 2016年 晏德智. All rights reserved.
//

#import "YuanXinPickerManager.h"

#if __has_include(<React/RCTBridge.h>)
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTUtils.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTImageLoader.h>
#else
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTUtils.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTImageLoader.h>
#endif
#import "ShareView.h"

@interface YuanXinPickerManager()<UINavigationControllerDelegate>

@end

@implementation YuanXinPickerManager

@synthesize bridge = _bridge;

RCT_EXPORT_MODULE();

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

/**
 * 调用弹框
 *
 * @param NSDictionary
 *
 * @return   @{ ImageName: 'shareToSession',
 Title: '微信好友',
 ImageSource: '',
 
 }
 */

RCT_EXPORT_METHOD(showShareView:(NSDictionary *)options resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)recject){
    
    UIViewController *controller = RCTPresentedViewController();
    
    if (controller == nil) {
        RCTLogError(@"Tried to display action sheet but there is no application window. options: %@", options);
        return;
    }
    
    @try {
        
        NSDictionary *layoutDict = [RCTConvert NSDictionary:options[@"Layout"]];
        //行数
        NSInteger maxLine = [RCTConvert NSInteger:layoutDict[@"maxLine"]];
        //列数
        NSInteger maxColume = [RCTConvert NSInteger:layoutDict[@"maxColume"]];
        //圆角
        CGFloat cornerRadius = [RCTConvert CGFloat:layoutDict[@"cornerRadius"]];
        //距离两边距离
        CGFloat theLengthToSide = [RCTConvert CGFloat:layoutDict[@"theLengthToSide"]];
        //滚动方向 0->竖着 1->横着
        ScrollDirection direction = [RCTConvert NSInteger:layoutDict[@"scrollDirection"]];
        //位置 0->居下  1->居中
        contentModel contentModel = [RCTConvert NSInteger:layoutDict[@"contentModel"]];
        
        NSArray *dataSource =   [RCTConvert NSDictionaryArray:options[@"Items"]];
        
        NSMutableArray *dataArr = [NSMutableArray new];
        
        if (dataSource.count > 0)
        {
            
            for (NSDictionary *dict in dataSource)
            {
                NSString *ImageName = [RCTConvert NSString:dict[@"Name"]];
                NSString *title = [RCTConvert NSString:dict[@"Title"]];
                NSString *ImageUrl = [RCTConvert NSString:dict[@"ImageSource"]];
                UIImage *image = [self getImageWithImageURL:ImageUrl AndImageName:ImageName];
                NSDictionary *temDict;
                if (image)
                {
                    temDict = @{@"Name":ImageName,@"Title":title,@"ImageSource":ImageUrl,@"image":image};
                    [dataArr addObject:temDict];
                    
                }else{
                    temDict = @{@"Name":ImageName,@"Title":title,@"ImageSource":ImageUrl};
                    [dataArr addObject:temDict];
                }
                
                
            }
            dataSource =nil;
            
        }
        
        ShareView *shareView = [[ShareView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        shareView.contentModel = contentModel;
        shareView.viewCornerRadius = cornerRadius;
        shareView.theLengthToSide = theLengthToSide;
        [shareView configShareViewWithMaxLine:maxLine MaxColume:maxColume Direction:direction DataArry:[dataArr copy]];
        __block RCTPromiseResolveBlock success = resolve;
        //__block RCTPromiseRejectBlock  error = recject;
        shareView.selectblock = ^(NSDictionary *dict){
            if (success){
                success(dict);
            }
        };
        
        if (controller.tabBarController != nil) {
            [controller.tabBarController.view addSubview:shareView];
        }else if (controller.navigationController != nil){
            [controller.navigationController.view addSubview:shareView];
        }else{
            [controller.view addSubview:shareView];
        }
    } @catch (NSException *exception) {
        //NSLog(@"An exception occurred: %@", exception.name);
        //NSLog(@"Here are some details: %@", exception.reason);
        NSDictionary *userInfo = @{ NSLocalizedDescriptionKey:exception.reason };
        NSError *errorInfo = [NSError errorWithDomain:exception.name
                                                 code:@(-1)
                                             userInfo:userInfo];
        recject(@(-1).stringValue, exception.name, errorInfo);
    } @finally {
    }
}

//获取图片
- (UIImage *)getImageWithImageURL:(NSString *)ImageURL
                     AndImageName:(NSString *)ImageName
{
    __block UIImage *imageNew ;
    
    if ([self allIsEmpty:ImageURL])
    {
        imageNew = [UIImage  imageNamed:ImageName];
    }else{
        
        /*       [self.bridge.imageLoader loadImageWithURLRequest:[NSURL URLWithString:ImageURL] callback:^(NSError *error, UIImage *image) {
        //                           imageNew = image;
        //
        //
        //        }];*/
        NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:ImageURL]];
        imageNew = [UIImage imageWithData:data];
        
    }
    
    
    return imageNew;
    
}

- (BOOL)allIsEmpty:(NSString *) str;
{
    if (!str) {
        return true;
    } else {
        NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        NSString *trimedString = [str stringByTrimmingCharactersInSet:set];
        if ([trimedString length] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

@end
